package com.rjjh.springmvc.easymvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class WebUtil {
    public static Properties prop = new Properties();

    static {
        try {
            Properties prop = new Properties();
            prop.load(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("mvc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //每一个 url 对应一个 Controller 方法
    public static Map<String, ControllerBean> urlMap = new HashMap<>();

    //初始化应用
    public static void initWebApp() {
        List<Class<?>> classList = ClassUtil.getClassListByAnnotation(prop.getProperty("mvc.scanPackags"), Controller.class);
        for (Class<?> clazz : classList) {
            Method[] controllerMethods = clazz.getDeclaredMethods();
            if (controllerMethods != null && controllerMethods.length > 0) {
                for (Method controllerMethod : controllerMethods) {
                    RequestMapping rm = controllerMethod.getAnnotation(RequestMapping.class);
                    if (rm != null) {
                        String url = rm.value();
                        urlMap.put(url, new ControllerBean(clazz, controllerMethod));
                    }
                }
            }
        }
    }

    //处理结果
    public static void handleResult(HttpServletRequest request, HttpServletResponse response, ModelAndView mv) throws Exception {
        String path = prop.getProperty("mvc.view_perfix") +
                mv.getViewName() + prop.getProperty("mvc.view_suffix");
        Map<String, Object> attrs = mv.getModel();
        for (Map.Entry<String, Object> entry : attrs.entrySet()) {
            request.setAttribute(entry.getKey(), entry.getValue());
        }
        request.getRequestDispatcher(path).forward(request, response);
    }


    public static ControllerBean getControllerBeanByUrl(String url) {
        return urlMap.get(url);
    }
}